<?php

class Kernel_Form_Order_Parent extends Kernel_Form_Order_Abstract 
{
    
    public function __construct($params = array()) 
    {
        if (true !== array_key_exists('parent', $params)) {
            trigger_error('Target parent must be specified in class definition', E_USER_ERROR);
        }
        
        parent::__construct($params);
    }
    
    
    public function addNode($position, $addit_values = array()) 
    {
        $addit_values[$this->parent_field] = $this->parent;
        return $this->_addNode($position, $addit_values);
    }
    
    public function moveNode($_id, $_position) 
    {
        // get position and parent of the editable element before it'll be moved
        $tmp_pos = $this->_getPosition($_id);
        $tmp_parent = $this->_getParent($_id);
        
        // if parent remains the same do simple move
        if ($tmp_parent == $this->parent) {
            return $this->_moveNode($_id, $_position);
        }
        
        
        // increment new parent elements positions starting with position
        // where editable element will be placed 
        $this->_increment(array_slice($this->_getValues(), $_position - 1));
        // and place element itself
        database::update($this->table, 
            array($this->parent_field => $this->parent, $this->pos_field => $_position), 
            array($this->id_field => $_id));
        
        // then decrement old parent elements starting with position the  
        // editable element had 
        $this->parent = $tmp_parent;
        $this->_decrement(array_slice($this->_getValues(), $tmp_pos - 1));
    }
    
    /**
    * @desc Delete node specified. 
    * 
    * @param integer $id
    */
    public function deleteNode($id) 
    {
        return $this->_deleteNode($id);
    }
    
    /**
     * @desc Form SQl statement. 
     *
     * @return  string
     */
    protected function _getQueryBody() 
    {
        $query = '
            SELECT 
                   `' . $this->id_field . '` 
              FROM 
                   `' . $this->table . '` 
             WHERE 
                   `' . $this->parent_field . '` ' 
                   . ($this->parent ? '= ' . (int)$this->parent : 'IS NULL'); 
        
        if (!is_null($this->condition)) {
            $query .= '
               AND 
                ' . database::condition($this->condition);
        }
        $query .= '
          ORDER BY 
                   `'. $this->pos_field . '`
               ASC 
            ';
        return $query;
    }
    
    /**
    * @desc Return parent for node specified. 
    * 
    * @return integer
    */
    protected function _getParent($id) 
    {
        $query = '
            SELECT 
                   `' . $this->parent_field . '` 
              FROM 
                   `' . $this->table . '` 
             WHERE 
                   `' . $this->id_field . '` = ' . (int)$id;
        return database::fetchOne($query);
    }
    
}
